package vpfarm.gui;

import java.io.IOException;
import java.net.UnknownHostException;

import jtools.ai.agenten.AMessage;
import jtools.ai.agenten.Agent;
import jtools.ai.agenten.Behavior;
import jtools.ai.agenten.Plattform;
import jtools.network.mqueue.Adress;
import jtools.network.mqueue.MessageException;
import vpfarm.Constants;
import vpfarm.slave.Slave;

public class SlaveMessageAgent extends Agent {

	public static final int PING = 1;
	public static final int START = 2;
	public static final int CLOSE = 3;
	private int status;
	private String target;
	private SlaveGUI gui = null;
	private int port;
	private String host;


	public SlaveMessageAgent(int ping2, String host, int port, String name, SlaveGUI gui) throws UnknownHostException, IOException, MessageException {
		super(new Adress(host, port));
		this.host = host;
		this.port = port;
		this.status = ping2;
		this.target = name;
		this.gui = gui;
	}

	
	public void onStart(){
		if (status == PING){
			addBehavior(new PingBehavior());
			new Thread(new Runnable(){
				public void run(){
					try {
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					removeAllBehavior();
				}
			}).start();
		}else if (status == START){
			try {
				
				new Slave(new Adress(host, port));
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (MessageException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else if (status == CLOSE){
			AMessage amsg = new AMessage(Constants.CLOSE_AGENT);
			amsg.addReciver(target);
			sendMessage(amsg);
		}
	}
	
	
	class PingBehavior extends Behavior{

		boolean done = false;
		boolean ping = false;
		public boolean done() {
			return done;
		}

		@Override
		public void execute() {
			AMessage amsg = reciveMessage(true);
			if (amsg.getSubject() == Constants.PING){
				gui.setMessage("Slave hat geantwortet");
				System.out.println("Slave hat geantwortet");
				done = true;
				ping = true;
			}else if (amsg.getSubject() == Constants.SEND_JOB_INFO){
			}else{
				ping = false;
				gui.setMessage("Erhalte unerwartete Nachricht, slave antwortet nicht");
				System.out.println("Erhalte unerwartete Nachricht, slave antwortet nicht");
				done = true;
			}
		}

		@Override
		public void onEnd() {
			if (!ping){
				gui.setMessage("Nach 3 sec. keine Antwort erhalten");
				System.out.println("Nach 3 sec. keine Antwort erhalten");
			}
		}

		@Override
		public void onStart() {
			AMessage amsg = new AMessage(Constants.PING);
			amsg.addReciver(target);
			sendMessage(amsg);			
		}
		
	}
}
